# -*- coding: UTF-8 -*-
# Author: Liang Bing
# E-mail: believer19940901@gmail.com
# Date Time: 2025/6/21 15:55

from pathlib import Path
import pandas as pd
from pandas import DataFrame


def open_excel(input_file: Path) -> DataFrame:
    """
    尝试打开 Excel 文件，如果失败则尝试作为制表符文本打开。

    :param input_file: 输入文件路径
    :return: 读取的 DataFrame
    :raises: Exception 当文件无法读取时
    """
    try:
        return pd.read_excel(input_file, sheet_name=0, engine="openpyxl")
    except Exception as xlsx_err:
        print(f"[Warning] 不是 Excel 格式文件：{input_file}，尝试以文本读取……")

        try:
            return pd.read_table(input_file, encoding="utf-8")
        except Exception as txt_err:
            print(f"[Error] 无法打开文件：{input_file}")
            print(f"[Detail] Excel 读取错误: {xlsx_err}")
            print(f"[Detail] 文本读取错误: {txt_err}")
            raise RuntimeError(f"无法解析文件 {input_file}") from txt_err
